<!-- 页面有刘浩搭建
@author 刘浩
@date   2023-8-4
-->
<template>
  <layout-card
    v-model="search"
    :filters="exampleOptions1"
    headline="信息列表"
    headtitle="数据筛选"
    :hasButton="true"
    @search-change="getData"
    @search-reset="searchReset"
  >
    <template #action>
      <el-button type="primary" @click="handleCreate">添加</el-button>
    </template>

    <table-common
      :loading="loading"
      @sort-change="handleSortChange"
      :columns="exampleColumns"
      :pagination="pager"
      :table-data="data"
      size="large"
      @current-change="myChangeCurrent"
      @size-change="myChangePageSize"
      stripe
    >
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button class="link-btn" @click="handleEdit(row)" link type="primary"
          >编辑</el-button
        >
        <el-popconfirm
          title="是否删除?"
          confirmButtonText="确定"
          cancelButtonText="取消"
          @confirm="() => handleDelete(row)"
        >
          <template #reference>
            <el-button class="link-btn" link type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>
  </layout-card>
  <edit-dialog
    :close-on-click-modal="false"
    :centerDialogVisible="centerDialogVisible"
    :tilte="addTilte"
    :key="timer"
    @Cancel="Cancel"
    @Submit="Submit"
  >
    <template #content>
      <FilterBar
        ref="dialogValue"
        :rules="myRules"
        :filters="dialogType"
        :hasButton="false"
      ></FilterBar>
    </template>
  </edit-dialog>
</template>

<script lang="ts" setup>
import { computed, ref, onBeforeMount, nextTick } from "vue";
// 7-18修改LayoutCard 页面，hasButton参数为false时显示为弹窗样式，为true时显示为搜索栏样式
import LayoutCard from "@/components/LayoutCard/index.vue";
import TableCommon from "@/components/TableCommon/index.vue";
import FilterBar from "@/components/FilterBar/index.vue";
import { myRules } from "./config/rules";

import {
  greyTypeList,
  addGreyType,
  upDateGreyType,
  deleteGreyType,
} from "@/api/pax/greytype";
import {
  exampleOptions1,
  dialogOptions,
  dialogEditOptions,
} from "./config/filters";
import { usePagination } from "vue-request";
import editDialog from "@/components/editDialog/index.vue";
import { exampleColumns } from "./config/columns";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
// ==========模拟接口数据-START
// 此处是模拟的接口返回数据，项目中请用`@/api/`下接口代替，删除当前代码！
const Service = () => {
  return new Promise(() => {
    // 模拟数据写入，实际开发使用接口数据写入
    // area1 这个值仅用于判断演示，根据实际情况进行编写
  });
};
// =============模拟接口数据==END

const {
  run,
  data,
  loading,
  current,
  pageSize,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  total,
  changeCurrent,
  changePageSize,
} = usePagination(Service, {
  manual: true,
  pagination: {
    currentKey: "pageNum",
    pageSizeKey: "pageSize",
    totalKey: "data.total",
  },
});

// 新增弹窗是否打开
const centerDialogVisible = ref(false);
// 弹窗标题
const addTilte = ref("新增问题类型");
// 弹窗页面类型
const dialogType = ref();
// 时间戳，用于确保弹窗页面能加载不同的界面
const timer = ref();
// const visible = ref(false)
// const isAdd = ref(true)
// const handleCreate = () => {
//   isAdd.value = true
//   visible.value = true
// }
// 7-17------------------
// 打开新增窗口
const handleCreate = () => {
  addTilte.value = "新增灰名单种类";
  timer.value = new Date().getTime();
  dialogType.value = dialogOptions;
  centerDialogVisible.value = true;
};
// 当前行的id
const rowId = ref("");
/* 编辑的回调
row 当前行
*/
const handleEdit = (row) => {
  rowId.value = row.typeId;
  dialogType.value = dialogEditOptions;
  // 该循环用于进行编辑页面数据回显，需要字段对应
  dialogEditOptions.forEach((e) => {
    if (row[e.prop] != null) {
      e.defaultValue = row[e.prop];
    }
  });
  timer.value = new Date().getTime();
  addTilte.value = "编辑灰名单种类";
  centerDialogVisible.value = true;
};
// 新增窗口点击取消
const Cancel = () => {
  centerDialogVisible.value = false;
  dialogType.value = "";
};

/*
排序的回调函数
column 是得到点击的哪一行
*/
const handleSortChange = (column: any) => {
  const prop = column.prop;
  let order = column.order;
  if (order === "descending") {
    order = "DESC";
  } else if (order === "ascending") {
    order = "ASC";
  }
  search.value.order = { column: prop, method: order };
  getData();
};
const dialogValue = ref({});
// 新增窗口点击确认
const { getters } = useStore();
//  拿到vuex里面的登录用户信息
const Users = computed(() => getters["user/getUserInfo"]);

// 用户信息
const creator = ref({});
creator.value.id = Users.value.userId;
creator.value.name = Users.value.userName;
creator.value.organId = Users.value.organId;
creator.value.organName = Users.value.organName;
const owner = ref({});
owner.value.id = Users.value.userId;
owner.value.name = Users.value.userName;
owner.value.type = "PERSONAL";
/**
 * 提交回调函数
 */
const Submit = async () => {
  const dialogParmas = ref({});
  dialogParmas.value = dialogValue.value.getParams();
  const { typeName } = dialogValue.value.getParams();
  const newtypename = typeName ? typeName.replace(/\s+/g, "") : typeName;
  await nextTick(() => {
    dialogValue.value.setFieldsValue({
      typeName: newtypename,
    });
  });
  if (addTilte.value === "新增灰名单种类") {
    // 调用新增方法
    dialogParmas.value.creator = creator.value;
    dialogParmas.value.owner = owner.value;
    const flag1 = await dialogValue.value?.validateRuleFormRef();
    if (flag1 === true) {
      const trimTypeName = dialogParmas.value.typeName.trim();
      const trimmedStr = trimTypeName.replace(/\s+/g, "");
      dialogParmas.value.typeName = trimmedStr;
      addGreyType(dialogParmas.value).then((res) => {
        if (res.code === "1") {
          getData();
          ElMessage.success("添加成功");
          centerDialogVisible.value = false;
        } else {
          ElMessage.error("灰名单种类名称重复");
        }
      });
    }
  } else {
    dialogParmas.value.typeId = rowId.value;
    dialogParmas.value.mender = creator.value;
    delete dialogParmas.value.lastUpdateTime;
    const flag1 = await dialogValue.value?.validateRuleFormRef();
    if (flag1 === true) {
      const trimTypeName = dialogParmas.value.typeName.trim();
      const trimmedStr = trimTypeName.replace(/\s+/g, "");
      dialogParmas.value.typeName = trimmedStr;
      upDateGreyType(dialogParmas.value).then((res) => {
        if (res.message === "change.success") {
          getData();
          ElMessage.success("编辑成功");
          centerDialogVisible.value = false;
        } else {
          ElMessage.error("灰名单种类名称重复");
        }
      });
    }
  }
};

// 删除 row 当前行
const handleDelete = (row: any) => {
  deleteGreyType({ typeId: `${row.typeId}` }).then((res) => {
    if (res.code === "200") {
      ElMessage.success(`${res.message}`);
      getData();
    } else {
      ElMessage.error(`${res.message}`);
    }
  });
};

// 7-17------------------
const pager = computed(() => ({
  currentPage: current.value,
  pageSize: pageSize.value,
  total: myTotal.value,
  // 7-24 手动设置了总页数
  pageCount:
    Math.ceil(myTotal.value / pageSize.value) === 0
      ? 1
      : Math.ceil(myTotal.value / pageSize.value),
}));
const search = ref<FilterDataType>({});
/*
重写清空查询
*/
const searchReset = (data: FilterDataType) => {
  search.value = data;
  pager.value.currentPage = 1;
  pager.value.pageSize = 10;
  getData();
};
const myTotal = ref(0);
// 获取数据
const getData = () => {
  if (search.value.lastUpdateTime && search.value.lastUpdateTime.length > 1) {
    search.value.timeStart = search.value?.lastUpdateTime[0];
    search.value.timeEnd = search.value?.lastUpdateTime[1];
    delete search.value.lastUpdateTime;
  } else {
    delete search.value.lastUpdateTime;
  }

  const params = {
    pageNum: current.value,
    pageSize: pageSize.value,
    condition: search.value,
  };
  /*
调用查询接口
params查询的参数
*/
  greyTypeList(params).then((res) => {
    data.value = res.data.list;
    myTotal.value = parseInt(res.data.total);
  });
  run(params);
  loading.value = false;
};

const myChangePageSize = (value: any) => {
  changePageSize(value);
  getData();
};
// 重写方法当前页
const myChangeCurrent = (value: any) => {
  changeCurrent(value);
  getData();
};

onBeforeMount(getData);
</script>
<style scoped>
.container {
  background: #f5f7f9;
  min-height: auto;
  overflow: hidden;
}
.container .card-content {
  padding: 10px;
  margin: 0;
  background: #fff;
  border-radius: 8px;
}
</style>
